/*
 *  Copyright 2011-2012 Redia A/S
 * 
 *  This file is part of Redias Android Utilities.
 *
 *  Redias Android Utilities is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redias Android Utilities is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redias Android Utilities.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.lib.xmlrpc;

import net.NetworkUtils;

import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCFault;

import dk.redia.lib.log.Log;
import dk.redia.lib.processing.ManagedAsyncTask;

public class XmlRpcClientCallTask extends ManagedAsyncTask<XmlRpcClientCall, Void, Object> {

	XmlRpcClientResultListener listener;
	
	private static final String logTag = "XmlRpcClientCallTask";
		
	@SuppressWarnings("unused")
	protected Object doInBackground(XmlRpcClientCall...calls ) {
		//XmlRpcClientCallTask.httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
		
		if (!NetworkUtils.getInstance().isOnline()) {
			return new XMLRPCFault("No network connection available", -0xffffff);
		}
		
		if (calls==null) {
			Log.e(logTag, "calls is null in XmlRpcClientCallTask.doInBackground()");
			return new XMLRPCFault("calls is null", -0xfffff0);
		}
		
		if (calls.length<=0 || calls[0]==null) {
			return new XMLRPCFault("No valid calls provided to XmlRpcClientCallTask", -0xfffffe);
		}
				
		try {
			this.listener = calls[0].resultListener;
			XMLRPCClient client = new XMLRPCClient(calls[0].url.toString(), calls[0].httpContext);
			if (isCancelled()) {
				return new XMLRPCFault("Request cancelled", -0xfffffc);
			}
			if (client!=null) {
				Object result = client.callEx(calls[0].methodName, calls[0].params);
				return result;
			} else {
				return new XMLRPCFault("Unable to create client", -0xfffffd);
			}
		} catch (Exception e) {
			return e;
		}
	}
	
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		if (this.listener==null) {
			Log.e(XmlRpcClientCallTask.logTag, "No listener in XmlRpcClientCallTask");
			return;
		}
		if (result instanceof XMLRPCFault ) {
			this.listener.callFailed(((XMLRPCFault) result).getMessage());
		} else if (result instanceof XMLRPCException) {
			this.listener.callFailed(((XMLRPCException) result).getMessage());
		} else {
			this.listener.callCompleted(result);
		}
	}
}
